import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import ProForm,{ ProFormSelect, ProFormDigit, ModalForm, ProFormTextArea, ProFormText, ProFormDateRangePicker, ProFormUploadDragger, DrawerForm, ProFormDatePicker, ProFormRadio } from '@ant-design/pro-form';
import {  Button,Popconfirm, message, InputNumber, Table, Form, Modal, Select } from 'antd';
import React from 'react';
import { Tabs } from 'antd';
const { TabPane } = Tabs;
import {Customer,ProductType,SaleTeam} from '../../model';
import { PlusOutlined  } from '@ant-design/icons';
import ProductNameChoose from './ProductNameChoose';
import CustomerChoose from './CustomerChoose';
import request from '@/utils/request';
import {manufacturerOption, priceLevelData,priceOption} from '@/utils/utils';
import { Space } from 'antd';
import { Spin } from 'antd';
const { Option } = Select;

class DealerAuth extends React.Component<any,any>{

  access = sessionStorage.getItem('access') as string;
  priceOption = priceOption();
  static propTypes:{
    data:any;
    callback:any;
  }
  
   constructor(props:any){
    super(props);
    if(sessionStorage.getItem('loginName')==='冯水华'){
      this.access = 'sale'
    }
    if(this.access==='checker'){
      this.access = 'sale'
    }
    if(this.access==='admin2'){
      this.access = 'sale'
    }
    this.state={
      moneyYear:0,
      moneyYear_2:0,
      proModalVisible:false,
      custModalVisible:false,
      currentKey:'',
      data:props.data,
      indicators:{},
      numProduct:[],
      editableKeys:[],
      salesList:[],
      product:[],
      showProduct:[],
      customer:[],
      dealer:[],
      dealerOne:[],
      currentColumn:[],
      currentData:[],
      requestFunction:{},
      proRowKey:[],
      priceFlag:false,
      priceData:[],
      currentPos:-1,
      priceValue:0,
      custPrice:0,
      currentLevel:'',
      currentPrice:'',
      dateRange:['',''],
      dateRangeFlag:false,
      priceTypes:[],
      batchPrice:'',
      spinningFlag:false,
      errorVisible:false,
      errInfo:[],
      zbForm:false,
      zbData:{},
      zbNewForm:false,
      productNameOption:{},
      depts:[],
      changePriceFlag:false,
      batchDepts:[],
      namesData:[{'manufacturer':'1','id':'1',product_name:'远端**导管',child:[
        {productStandard:'SM*DAC-11111',price:'￥6,000.00',authType:'普通授权',authDate:'2022-01-01~2022-12-31',priceLevel:'A级达标'},
        {productStandard:'SM*DAC-22222',price:'￥6,000.00',authType:'普通授权',authDate:'2022-01-01~2022-12-31',priceLevel:'A级达标'},
        {productStandard:'SM*DAC-33333',price:'￥6,000.00',authType:'普通授权',authDate:'2022-01-01~2022-12-31',priceLevel:'A级达标'}]}
      ,{'manufacturer':'1','id':'2',product_name:'颅内**导管',child:[
        {productStandard:'WM*DAC-11111',price:'￥6,000.00',authType:'普通授权',authDate:'2022-01-01~2022-12-31',priceLevel:'A级达标'},
        {productStandard:'WM*DAC-22222',price:'￥6,000.00',authType:'普通授权',authDate:'2022-01-01~2022-12-31',priceLevel:'A级达标'},
        {productStandard:'WM*DAC-33333',price:'￥6,000.00',authType:'普通授权',authDate:'2022-01-01~2022-12-31',priceLevel:'A级达标'}]}]
    }
   }

   proRef = React.createRef<any>();
   customerRef = React.createRef<any>();
   zbAction = React.createRef<any>();
   zbRef = React.createRef<any>();
   formRef = React.createRef<any>();
   tab2FormRef = React.createRef<any>();
  salesTeamData =(params:any)=>{
      var data =  request('/xwyl/salesTeam/salesTeamData',{params});
      return data;
  }

  dealerData =(params:any)=>{
    var levelParam = {level:'二级'};
    var data =  request('/xwyl/dealer/dealerListData', { params:{...params,...levelParam}});
    return data;
  }

  indicatorsDataByDealerId =async(params:any)=>{
    var data =  request('/xwyl/sign/indicatorsDataByDealerId', { params:params});
    return data;
  }

  dealerDataOne =(params:any)=>{
    var levelParam = {level:'一级'};
    var data =  request('/xwyl/dealer/dealerListData', { params:{...params,...levelParam}});
    return data;
  }

  updatePrice=(params:any)=>{
    var data =  request('/xwyl/dealerNew/updatePrice', {params});
    return data;
  }

  proData =(params:any)=>{
    let ids = this.state.product.map(function (item:any) {
      return item.id;
    });
    var pos = params.currentPrice;    
    if(pos){
      params.manufacturer = pos.split('.')[0]
      params.sort = pos.split('.')[1]
    }
    params.checkedIds = ids.join(',');
    // if(this.formRef.current.getFieldValue('priceLevel')){
    //   params.group = priceLevelData().filter((item)=>item.value == this.formRef.current.getFieldValue('priceLevel'))[0].label
    // }
    return request('/xwyl/product/productDataNew', {
      method: 'POST',
      requestType:'form',
      data: {
        ...params,
        method: 'post',
      },
    });
  }

  custData = (params:any)=>{
    var data = request('/xwyl/hospital/hospitalData?isAll=1',{params});
    return data;
  }
  async requestProductName(){
    var params:any = {pageSize: 1000}
    var res = await request('/xwyl/product/productData?pageSize=1000',params);
    var obj = {};
    res.data = res.data.reduce(function (item: any, next: any) {
      if (!obj[next.product_name]) {
        obj[next.product_name] = {
          text: next.product_name
        };
        item.push(next);
      }

      return item;
    }, []);
    this.setState({productNameOption:obj})
  }

  async tab1Data() {
    var data =  request('/xwyl/indicators/authorizationData?dealerId='+this.state.data.dealId);
    var val =await data;
    if(val.errorCode==='200'){
      val.data.salesList.forEach((element:any) => {
        element.id = element.salesId;
        element.name= element.salesName;
      });
      val.data.product.forEach((element:any)  => {
        element.id = element.productId;
      });
      val.data.customer.forEach((element:any)  => {
        element.id = element.customerId;
        element.name = element.customerName;
        element.depts = element.hdList.map((item:any)=>item.id)
      });
      val.data.authorization.forEach((element:any)  => {
        element.id = element.child_dealerId;
        element.cnName= element.child_dealerName;
      });
      this.formRef.current?.setFieldsValue({level:val.data.dealer.level,liable:val.data.dealer.liable,count_activation:val.data.dealer.count_activation,'customerName':val.data.dealer.customerName,priceLevel:val.data.dealer.priceLevel,discount:val.data.dealer.discount,remark:val.data.dealer.remark});
      var valPrice = await request(`/xwyl/priceGrade/getDealerPriceGrade?dealerId=${this.state.data.dealId}&group=${val.data.dealer.priceLevel}`);
      var priceTypes:any = []
      if(valPrice.errorCode==='200'){
        priceTypes = valPrice.data.map((item:any)=>{
          return {label:item.name,value:`${item.manufacturer}.${item.sort}`}
        })
      }
      this.setState({priceTypes:priceTypes,salesList:val.data.salesList,customer:val.data.customer,dealerOne:val.data.dealerOne,dealer:val.data.authorization,product:val.data.product,showProduct:val.data.product,currentLevel:val.data.dealer.level});
    }else{
      message.error('获取授权信息失败');
    }
  }

  deptData=async()=>{
    var data =  request('/xwyl/hospitalDepartment/listHospitalDepartment');
    var val =await data;
    this.setState({depts:val.data.map((item:any)=>{
     return {label:item.name,value:item.id}
   })})
  }
   componentDidMount(){
    this.tab1Data();
    this.deptData();

    this.requestProductName()

  }

  deleteItem=(stateKey:any,byId:any)=>{
    var newData=this.state[stateKey].filter((item:any) => item.id !== byId);
    this.setState({[stateKey]:newData});
  }

  zbColumn:ProColumns<any>[] = [
    {
      title: '厂家',
      dataIndex: 'manufacturer',
      valueType:'select',
      width:100,
      valueEnum:manufacturerOption(),
    },
    {
      title: '年度',
      dataIndex: 'year',
      hideInSearch:true
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record:any,_, action) => 
        <a
          key='editable'
          onClick={async () => {
            console.log(record.targetList)
            this.setState({zbData:record,zbForm:true,moneyYear:record.annual_indicators,numProduct:record.targetList})
          }}
        >
          详情
        </a>
      
    }
  ]

  dealerColumn:ProColumns<any>[] = [
    {
      title:'名称',
      dataIndex: 'cnName',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
      <Popconfirm title='确定删除该客户吗?' key='delete' onConfirm={() => {
        if(this.state.currentLevel==='一级'){
          this.deleteItem('dealer',record.id)
        }else{
          this.deleteItem('dealerOne',record.id)
        }
      }}>
        <a hidden={this.access==='sale'}>删除</a>
      </Popconfirm>
      ]
    },
  ]

  saleColumn:ProColumns[] = [
    {
      title:'姓名',
      dataIndex: 'name',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
      <Popconfirm title='确定删除该销售吗?' key='delete' onConfirm={() => this.deleteItem('salesList',record.id)}>
        <a hidden={this.access==='sale'}>删除</a>
      </Popconfirm>
      ]
    },
  ]

  errorColumn=[
    {
      title: '错误行',
      dataIndex: 'rownum',
    },
    {
      title: '错误信息',
      dataIndex: 'errerMsg',
    },
  ]

 //表头信息以及表值设置
  cColumns: ProColumns<Customer>[] = [
    {
      width:200,
      ellipsis:true,
      title:'客户名称',
      dataIndex: 'name',
    },
    {
      title: '客户类型',
      dataIndex: 'category',
      hideInSearch:true,
      sorter: (a:any, b:any) => a.category - b.category,
      valueEnum: {
        1: { text: '医院' },
        2: { text: '商业客户' },
      },
    },
    {
      title:'起始日期',
      dataIndex: 'start_time',
    },
    {
      title:'到期日期',
      dataIndex: 'deadline',
    },
    {
      title:'授权科室',
      width:200,
      dataIndex: 'depts',
      renderText:(_,record:any)=>{
        if(record.category==2){
          return ''
        }
        var showData:any = []
        let  obj ={};
        this.state.depts.forEach((item:any) => {
          if(!obj[item.value]){
            obj[item.value] = item.label
          }
        });
        if(record.depts){
          record.depts.forEach((item:any)=>{
              if(obj[item]){
                showData.push(obj[item])
              }
        })
      }
        return showData.join(',')
      }
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
      <Popconfirm title='确定删除该客户吗?' key='delete' onConfirm={() => this.deleteItem('customer',record.id)}>
        <a hidden={this.access==='sale'}>删除</a>
      </Popconfirm>
      ]
    },
    
  ];

 //表头信息以及表值设置
  pColumns: ProColumns<ProductType>[] = [
    {
      title: '产品名称',
      hideInSearch:true,
      editable:false,
      dataIndex: 'name',
    },
  ];

  onCleanSelected:any = {}

  chooseProColumn: ProColumns<ProductType>[] = [
    {
      title: '厂家',
      dataIndex: 'manufacturer',
      valueType:'select',
      valueEnum:manufacturerOption(),
      hideInSearch:true
    },
    {
      title: '价格体系',
      dataIndex: 'currentPrice',
      valueType:'select',
      valueEnum:()=>{
        var map:any = {}
        this.state.priceTypes.forEach((item:any) => {
            map[item.value] = {text:item.label}
        });
        return map
      },
      hideInTable:true
    },

    {
      title:'产品型号',
      dataIndex: 'product_standard',
    },
    {
      title: '产品名称',
      dataIndex: 'product_name',
      valueType:'select',
      valueEnum:()=>{
        return this.state.productNameOption
      }
    },
    {
      title: '价格',
      dataIndex: 'standard_price',
      hideInSearch:true,
      width:120,
      valueType:'money',
      renderText:(_,record:any)=>{
        return record.select_price[0]?.standard_price
      }
    }
  ];


  chooseDealerColumn: ProColumns<ProductType>[] = [
    {
      title:'编码',
      dataIndex: 'loginName',
    },
    {
      title:'客户名称',
      dataIndex: 'cnName',
    },
  ];


  chooseSaleColumn: ProColumns<ProductType>[] = [
    {
      title:'姓名',
      width:100,
      dataIndex: 'name',
    },
    {
      title:'岗位',
      dataIndex: 'part',
    },

    {
      title: '一线管理',
      width: 100,
      dataIndex: 'pName',
      hideInSearch:true,
    },
    {
      title: '二线管理',
      width: 100,
      dataIndex: 'superior',
      hideInSearch:true,
    }
  ];

  chooseCustomer: ProColumns<ProductType>[] = [
    {
      title:'客户编码',
      dataIndex: 'bh',
      width:100
    },
    {
      title:'客户名称',
      dataIndex: 'name',
    },
    {
      title:'客户类型',
      width:100,
      dataIndex: 'category',
      hideInSearch:true,
      valueEnum: {
        1: { text: '医院' },
        2: { text: '商业客户' },
      },
    },
  ];


  targetColumns: ProColumns<ProductType>[] = [

    {
      title: '产品名称',
      dataIndex: 'product_name',
      editable:false
    },
    {
      title: '一季度(件)',
      dataIndex: 'first_indicators',
      width:100,
      valueType:'digit',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },
    {
      title: '二季度(件)',
      dataIndex: 'second_indicators',
      width:100,
      valueType:'digit',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },
    {
      title: '三季度(件)',
      dataIndex: 'third_indicators',
      width:100,
      valueType:'digit',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },
    {
      title: '四季度(件)',
      dataIndex: 'fourth_indicators',
      width:100,
      valueType:'digit',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },
    {
      title: '年度(件)',
      dataIndex: 'year',
      width:100,
      valueType:'digit',
      editable:false
    },
    {
      title: '操作',
      valueType: 'option',
      width:140,
      render: (text, record,_, action) => [
        <a
          key='editable'
          onClick={() => {
            action.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];


  inputChange=()=>{
    var m1:number = this.tab2FormRef.current.getFieldValue('first_indicators');
    var m2:number = this.tab2FormRef.current.getFieldValue('second_indicators');
    var m3:number = this.tab2FormRef.current.getFieldValue('third_indicators');
    var m4:number = this.tab2FormRef.current.getFieldValue('fourth_indicators');
    this.setState({moneyYear:m1+m2+m3+m4});
  }


  onChange = (e:any) => {
    this.setState({
      priceValue: e.target.value,
    });
  };

  expandedRowRender = (val:any) => {
    const columns = [
      {
        title: '产品型号',
        dataIndex: 'productStandard',
      },
      {
        title: '产品价格',
        dataIndex: 'price',
      },
      {
        title: '授权类型',
        dataIndex: 'authType',
      },
      {
        title: '授权有效期',
        dataIndex: 'authDate',
      },
      {
        title: '价格等级',
        dataIndex: 'priceLevel',
      },
    ];
    const onSelectChange = (newSelectedRowKeys:any) => {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      // setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
      selectedRowKeys:this.state.selectedRowKeys,
      onChange: onSelectChange,
      selections: [
        Table.SELECTION_ALL,
        Table.SELECTION_INVERT,
        Table.SELECTION_NONE,
      ],
    };
    return <Table rowSelection={rowSelection} pagination={false} rowKey='productStandard' size='small' columns={columns} dataSource={val.child} />;
  };


    render(){
        return (
          <ProForm formRef={this.formRef}
                        submitter={this.access==='sale'?false:{
                            render: (props, defaultDoms) => {
                              return <div style={{margin:20}}>{defaultDoms[1]}</div>;
                            }
                          }}
                         onFinish={async (values) => {
                          var params:any={dealer:{},sales:[],customer:[],product:[],authorization:[]};
                          params.dealer.dealerId=this.state.data.dealId;
                          if(values.level==='一级'){
                            params.dealer.level='一级';
                          }else{
                            params.dealer.level='二级';
                          }
                          params.dealer.remark=values.remark
                          params.dealer.priceLevel=values.priceLevel;
                          params.dealer.liable=values.liable;
                          params.dealer.count_activation = values.count_activation;
                          params.dealer.customerName=values.customerName;
                          params.dealer.dealerId=this.state.data.dealId;
                          this.state.salesList.forEach((item:any)  => {
                            params.sales.push({salesId:item.id});
                          });
                          this.state.customer.forEach((item:any)  => {
                            params.customer.push({customerId:item.id,'start_time':item.start_time,'deadline':item.deadline,'hos_dept_ids':item.depts?item.depts.join(","):''});
                          });
                          this.state.product.forEach((item:any) => {
                                params.product.push({productId:item.id,priceId:item.priceId,price:item.standard_price});
                          });
                          this.state.dealer.forEach((item:any)  => {
                            params.authorization.push({dealerId:item.id});
                          });
                          var val = await request('/xwyl/indicators/approveDealer', {
                            method: 'POST',
                            headers:{
                              'Content-Type': 'application/json',
                              'authorization':`${sessionStorage.getItem('token')}`
                            },
                            data: {
                              ...params,
                              method: 'post',
                            },
                          });
                          if(val.errorCode==='200'){
                            if(this.state.currentLevel==='二级'){
                              var oneParam:any = []
                              this.state.dealerOne.forEach((item:any)  => {
                                oneParam.push({dealerId:item.dealerId?item.dealerId:item.id,child_dealerId:this.state.data.dealId,'child_dealerName':this.state.data.name});
                              });
                              val = await request('/xwyl/dealer/choiceDealer', {
                                method: 'POST',
                                headers:{
                                  'Content-Type': 'application/json',
                                  'authorization':`${sessionStorage.getItem('token')}`
                                },
                                data:oneParam
                              });
                            }
                            this.props.callback();
                            message.success('提交成功');
                            return true;
                          }else{
                            message.error(val.msg);
                            return false;
                          }
                        }}>
            <Tabs defaultActiveKey='1' centered>
                <TabPane tab='订单' key='1'>
                        <ProForm.Group style={{marginLeft:'25px'}}>
                        <ProFormText width='md' label='授权客户名称(中文)' name='customerName' />
                        </ProForm.Group>
                        <ProTable<SaleTeam>
                            headerTitle='授权销售'
                            dataSource={this.state.salesList}
                            columns={this.saleColumn}
                            rowKey='id'
                            key='sale'
                            search={false}
                            toolBarRender={() => [
                                <Button
                                type='primary'
                                key='primary'
                                hidden={this.access==='sale'}
                                onClick={() => {
                                  this.setState({custModalVisible:true,dateRangeFlag:false,currentData:this.state.salesList,currentColumn:this.chooseSaleColumn,requestFunction:this.salesTeamData,currentKey:'salesList'});
                                }}
                                >
                                <PlusOutlined />选择
                                </Button>
                            ]}
                            toolbar={{settings:[]}}
                            pagination={false}
                            />
                       <div hidden={this.state.currentLevel==='二级'} key='div3'>
                        <ProTable<SaleTeam>
                              headerTitle='授权二级客户'
                              dataSource={this.state.dealer}
                              columns={this.dealerColumn}
                              rowKey='id'
                              search={false}
                              key='dealer'
                              toolbar={{settings:[]}}
                              pagination={false}
                              />
                      </div>
                      <div hidden={this.state.currentLevel!='二级'} key='div2'>
                        <ProTable<SaleTeam>
                              headerTitle='授权一级客户'
                              dataSource={this.state.dealerOne}
                              columns={this.dealerColumn}
                              rowKey='id'
                              key='dealer1'
                              search={false}
                              toolBarRender={() => [
                                  <Button
                                  type='primary'
                                  key='primary'
                                  hidden={this.access==='sale'}
                                  onClick={() => {
                                    this.setState({custModalVisible:true,dateRangeFlag:false,currentData:this.state.dealerOne,currentColumn:this.chooseDealerColumn,requestFunction:this.dealerDataOne,currentKey:'dealerOne'});
                                  }}
                                  >
                                  <PlusOutlined />选择
                                  </Button>
                              ]}
                              toolbar={{settings:[]}}
                              pagination={false}
                              />
                      </div>
                      <div hidden={this.state.currentLevel==='二级'} key='label2'>
                        <div style={{marginLeft:25,width:600,marginTop:20}}>
                          <h3>授权产品备注</h3>
                          <ProFormTextArea name='remark' label='' placeholder='请填写授权产品备注'  allowClear={true} />
                        </div>
                        <ProTable
                            headerTitle={`授权产品(合计：${this.state.product.length})`}
                            columns={this.pColumns}
                            search={false}
                            pagination={false} 
                            rowKey="id"
                            toolbar={{settings:[],}}
                            dataSource={[{id:'0001',name:'多孔腔镜手术机器人'}]}
                            size="small"
                            toolBarRender={() => [
                              <Form.Item style={{marginBottom:-20}}>
                              <ProFormDigit width={'sm'} style={{marginBottom:0}} placeholder="请输入自定义价格" fieldProps={{onChange:(val:any)=>{
                                  this.setState({batchPrice:val})
                                }}} name='batchPrice'></ProFormDigit>
                              </Form.Item>,
                              <a key='i1' onClick={()=>{
                              }}>自定义价格设置</a>
                          ]}
                        />
                      </div>
                      <CustomerChoose
                            onCancel={() => {
                              this.setState({custModalVisible:false});
                            }}
                            onSubmit={(value:any) => {
                              var key = this.state.currentKey;
                              if(key==='product'){
                                // var xwSort = -1;
                                // var wmSort = -1;
                                // for(var i=0;i<this.state.product.length;i++){
                                //   if(this.state.product[i].manufacturer===1&&this.state.product[i].sort>=0&&this.state.product[i].sort<4){
                                //     xwSort = this.state.product[i].sort
                                //     break;
                                //   }
                                // }
                                // for(var i=0;i<this.state.product.length;i++){
                                //   if(this.state.product[i].manufacturer===2&&this.state.product[i].sort>=0&&this.state.product[i].sort<4){
                                //     wmSort = this.state.product[i].sort
                                //     break;
                                //   }
                                // }        
                                // if(xwSort===-1){
                                //   if(this.state.priceTypes[0].label.indexOf('A')>=0){
                                //     xwSort=1
                                //   }else if(this.state.priceTypes[0].label.indexOf('B')>=0){
                                //     xwSort=2
                                //   }
                                // }
                                // if(wmSort===-1){
                                //   if(this.state.priceTypes[0].label.indexOf('A')>=0){
                                //     wmSort=1
                                //   }else if(this.state.priceTypes[0].label.indexOf('B')>=0){
                                //     wmSort=2
                                //   }
                                // }
                                // value.forEach((item:any)=>{
                                //   if(item.manufacturer===1){
                                //     item.sort = xwSort
                                //     if(xwSort===-1){
                                //       item.standard_price=0;
                                //     }
                                //     else if(xwSort===0){
                                //       item.standard_price=item.select_price[3]?.standard_price;
                                //       item.priceId =item.select_price[3]?.priceId;
                                //     }else{
                                //       item.standard_price=item.select_price[xwSort-1]?.standard_price;
                                //       item.priceId =item.select_price[xwSort-1]?.priceId;
                                //     }
                                //   }else{
                                //     item.sort = wmSort
                                //     if(wmSort===-1){
                                //       item.standard_price=0;
                                //     }
                                //     else if(wmSort===0){
                                //       item.standard_price=item.select_price[3]?.standard_price;
                                //       item.priceId =item.select_price[3]?.priceId;
                                //     }else{
                                //       item.standard_price=item.select_price[wmSort-1]?.standard_price;
                                //       item.priceId =item.select_price[wmSort-1]?.priceId;
                                //     }
                                //   }
                                //   item.change = true
                                // })
                                value.forEach((item:any)=>{
                                  item.sort = item.select_price[0]?.sort;
                                  item.standard_price=item.select_price[0]?.standard_price;
                                  item.priceId =item.select_price[0]?.priceId;
                                })
                              }
                              
                              var data:any=[...value,...this.state[this.state.currentKey]]
                              if(this.state.currentKey==='product'){
                                this.setState({custModalVisible:false,[key]:data,showProduct:data});
                              }else{
                                this.setState({custModalVisible:false,[key]:data});
                              }
                            }}
                            modalVisible={this.state.custModalVisible}
                            values={this.state.currentData}
                            columns={this.state.currentColumn}
                            dateRangeFlag={this.state.dateRangeFlag}
                            requestFunction={this.state.requestFunction}
                        />
                       <ProductNameChoose
                            onCancel={() => {
                              this.setState({proModalVisible:false});
                            }}
                            onSubmit={async (value) => {
                              var data=[...value,...this.state.numProduct]
                              this.setState({proModalVisible:false,numProduct:data});
                            }}
                            modalVisible={this.state.proModalVisible}
                            values={this.state.numProduct}
                       />
                       <ModalForm
                        title="价格设置"
                        modalProps={{
                          forceRender: true,
                            destroyOnClose: true,
                        }}
                        visible={this.state.changePriceFlag}
                        onVisibleChange={(val)=>{
                          this.setState({changePriceFlag:val})
                        }}
                        onFinish={async(value)=>{
                            if(value.flag==='1'){
                              var pos = value.price;
                                this.setState({spinningFlag:true})
                                var param:any = {dealerId:this.state.data.dealId,changeDiy:0}
                                param.manufacturer = pos.split('.')[0]
                                param.priceGrade = pos.split('.')[1]
                                var val = await this.updatePrice(param);
                                this.setState({spinningFlag:false})
                                if(val.errorCode==='200'){
                                  message.info('价格修改成功！')
                                  this.props.callback();
                                  return true
                                }else{
                                  message.error(val.errorMessage);
                                  return false
                                }
                            }else{
                              var pos = value.price;  
                                this.setState({spinningFlag:true})
                                var param:any = {dealerId:this.state.data.dealId,changeDiy:1}
                                param.manufacturer = pos.split('.')[0]
                                param.priceGrade = pos.split('.')[1]
                                param.rownum=4
                                var val = await this.updatePrice(param);
                                this.setState({spinningFlag:false})
                                if(val.errorCode==='200'){
                                  message.info('价格修改成功！')
                                  this.props.callback();
                                  return true;
                                }else{
                                  message.error(val.errorMessage);
                                  return false;
                                }
                            }
                      
                        }}>
                          <ProFormSelect  key='price1' rules={[{ required: true, message: '请先选择' }]} name='price' label='价格体系' allowClear={false} placeholder='请选择价格等级'   width='xl'
                            options={this.state.priceTypes} />
                            <ProFormRadio.Group  rules={[{ required: true}]}   label="是否同步修改自定义价格？" name="flag"    width='xl' options={[{label:'是',value:'1'}, {label:'否',value:'0'}]}  />
                        </ModalForm>
                       <Spin spinning={this.state.spinningFlag} style={{transform:'translate(-50%,-50%)',left:'50%',top:'50%',position:'absolute'}}/>
                    
                </TabPane>
                <TabPane tab='客户' key='2'>
                <ProTable<Customer>
                          actionRef = {this.customerRef}
                          headerTitle={'授权客户(合计：'+this.state.customer.length+')'}
                          dataSource={this.state.customer}
                          columns={this.cColumns}
                          rowKey='id'
                          search={false}
                          tableAlertOptionRender={({selectedRowKeys,onCleanSelected}) => {
                            return (
                              <Space size={16}>
                                <a key='i2' style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                                  取消选择
                                </a>
                                <Form.Item style={{marginBottom:5,maxWidth:200,minWidth:200}}>
                                <Select  mode="multiple" placeholder="请选择科室" defaultValue={[]}
                                      style={{ width: '100%' }}
                                      onChange={(value)=>{
                                        // record.depts = value
                                        this.setState({batchDepts:value})
                                      }}
                                      allowClear>
                                        {this.state.depts.map((item:any)=>{
                                          return <Option value={item.value} key={item.value}>{item.label}</Option>
                                        })}
                                      </Select>
                                </Form.Item>
                                <a key='i1' onClick={()=>{
                                    var exist = (array:any,key:string)=>{
                                      var flag = false;
                                      for(var i=0;i<array.length;i++){
                                        if(array[i]===key){
                                          flag=true;
                                          break;
                                        }
                                      }
                                      return flag;
                                    };
                                    this.state.customer.forEach((element:any) => {
                                      if(exist(selectedRowKeys,element.id)&&element.category==1){
                                        element.depts = this.state.batchDepts
                                      }
                                    });
                                    // console.log(this.state.batchDepts,this.state.customer)
                                    this.setState({customer:this.state.customer})
                                    // this.customerRef.current?.reloadAndRest?.();
                                  }}>设置科室</a>
                                <Form.Item style={{marginBottom:-20}}>
                                  <ProFormDateRangePicker style={{marginBottom:0}} fieldProps={{onChange:(val:any)=>{
                                      if(val){
                                        this.setState({dateRange:[val[0].format('YYYY-MM-DD'),val[1].format('YYYY-MM-DD')]})
                                      }else{
                                        this.setState({dateRange:['','']})
                                      }
                                    }}} name='hosDate'></ProFormDateRangePicker>
                                </Form.Item>
                               
                                  <a key='i1' onClick={()=>{
                                    if(this.state.dateRange[0]===''){
                                      message.warning('请先选择授权期限')
                                      return;
                                    }
                                    var exist = (array:any,key:string)=>{
                                      var flag = false;
                                      for(var i=0;i<array.length;i++){
                                        if(array[i]===key){
                                          flag=true;
                                          break;
                                        }
                                      }
                                      return flag;
                                    };
                                    this.state.customer.forEach((element:any) => {
                                      if(exist(selectedRowKeys,element.id)){
                                        element.start_time = this.state.dateRange[0]
                                        element.deadline = this.state.dateRange[1]
                                      }
                                    });
                                    this.setState({customer:this.state.customer})
                                    // this.customerRef.current?.reloadAndRest?.();
                                  }}>设置授权期限</a>
                              </Space>
                            );
                          }}
                          rowSelection={{
                            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                          }}
                          toolBarRender={() => [
                              <Button
                              type='primary'
                              key='primary'
                              hidden={this.access==='sale'}
                              onClick={() => {
                                this.setState({custModalVisible:true,dateRangeFlag:true,currentData:this.state.customer,currentColumn:this.chooseCustomer,requestFunction:this.custData,currentKey:'customer'});
                              }}
                              >
                              <PlusOutlined />选择
                              </Button>
                          ]}
                          toolbar={{settings:[]}}
                          pagination={{
                            pageSizeOptions:['20', '100', '500']
                          }}
                      />
                {/* <ProTable
                  actionRef={this.zbAction}
                  columns={this.zbColumn}
                  rowKey='id'
                  request={async(params:any, sorter, filter) => {
                      params.dealerId=this.state.data.dealId
                      return this.indicatorsDataByDealerId({...params,filter})
                    }
                  }
                  pagination={{
                    pageSizeOptions:['20', '100', '500']
                  }}
                  toolBarRender={()=>[<Button
                    type='primary'
                    key='new'
                    onClick={() => {
                      this.setState({zbNewForm:true})
                    }}
                    >新增
                    </Button>]}
                  toolbar={{settings:[]}}/>
                  <DrawerForm
                    width={1000}
                    onVisibleChange={v=>{
                      this.setState({zbForm:v})
                    }}
                    drawerProps={{
                      destroyOnClose:true,
                      forceRender:true
                    }}
                    visible={this.state.zbForm}
                    submitter={this.access==='sale'?false:{
                      render: (props, defaultDoms) => {
                        return <div style={{margin:20}}>{defaultDoms[1]}</div>;
                      }}}
                    formRef={this.tab2FormRef}
                    onFinish={async (values) => {
                      values.year = this.state.zbData.year
                      values.annual_indicators = values.first_indicators+values.second_indicators+values.third_indicators+values.fourth_indicators;
                      values.dealerId = this.state.data.dealId
                      values.id = this.state.zbData.id
                      values.manufacturer = this.state.zbData.manufacturer
                      values.targetList = this.state.numProduct
                      values.targetList.forEach((item:any)=>{
                        item.dealerId = this.state.data.dealId
                        item.manufacturer = this.state.zbData.manufacturer
                      })
                      var val = await request('/xwyl/sign/saveIndicators',{ method: 'POST',
                      headers:{
                        'Content-Type': 'application/json',
                        'authorization':`${sessionStorage.getItem('token')}`
                      },
                      data: {
                        ...values,
                        method: 'post',
                      }});
                      if(val.errorCode==='200'){
                        message.success('提交成功');
                        this.props.callback();
                        return true;
                      }else{
                        message.error(val.errorMessage);
                        return false;
                      }
                    }}>
                        <div key='zbView' style={{marginLeft:20}}>
                          <h4 style={{color:'#CC3333'}}>订货额指标</h4>
                            <ProForm.Group>
                              <ProFormDigit  name='first_indicators' label='第一季度(元)' placeholder='请输入第一季度'  width={200} initialValue={this.state.zbData?.first_indicators}
                              fieldProps={{onBlur:this.inputChange}}/>
                              <ProFormDigit  name='second_indicators' label='第二季度(元)' placeholder='请输入第二季度'  width={200} initialValue={this.state.zbData?.second_indicators}
                            fieldProps={{onBlur:this.inputChange}}/>
                              <ProFormDigit  name='third_indicators' label='第三季度(元)' placeholder='请输入第三季度'  width={200} initialValue={this.state.zbData?.third_indicators}
                              fieldProps={{onBlur:this.inputChange}}/>
                              <ProFormDigit  name='fourth_indicators' label='第四季度(元)' placeholder='请输入第四季度'  width={200} initialValue={this.state.zbData?.fourth_indicators}
                          fieldProps={{onBlur:this.inputChange}}/>
                            </ProForm.Group>

                            <UpDownLabel title='年订货额指标' texts={['￥'+moneyFormat(this.state.moneyYear)]}/>

                            <h4 style={{color:'#CC3333'}}>产品数量指标</h4>
                            </div>
                            <ProTable<ProductType>
                              dataSource={this.state.numProduct}
                              columns={this.targetColumns}
                              rowKey='id'
                              formRef={this.zbRef}
                              search={false}
                              key='pnum'
                              toolBarRender={() => [
                                  <Button
                                  hidden={this.access==='sale'}
                                  type='primary'
                                  key='primary'
                                  onClick={() => {
                                    this.setState({proModalVisible:true});
                                  }}
                                  >
                                  <PlusOutlined />选择
                                  </Button>
                              ]}
                              toolbar={{settings:[]}}
                              pagination={false}
                              editable={{
                                type: 'multiple',
                                editableKeys,
                                onSave: async (v,data:any) => {
                                  var array=this.state.numProduct;
                                  array.forEach((item:any) => {
                                    if(item.id===data.id){
                                      item.first_indicators=data.first_indicators;
                                      item.second_indicators=data.second_indicators;
                                      item.third_indicators=data.third_indicators;
                                      item.fourth_indicators=data.fourth_indicators;
                                      data.year = data.first_indicators+data.second_indicators+data.third_indicators+data.fourth_indicators;
                                      item.year=data.year;
                                    }
                                  });
                                  this.setState({numProduct:array});
                                },
                                onDelete:async(v)=>{
                                  var newData=this.state.numProduct.filter((item:any) => item.id !== v);
                                  this.setState({numProduct:newData});
                                },
                                onChange: (v=>{
                                  this.setState({editableKeys:v})
                                }),
                              }}
                              />
                    </DrawerForm>
                    <DrawerForm
                    width={1000}
                    onVisibleChange={v=>{
                      this.setState({zbNewForm:v})
                    }}
                    drawerProps={{
                      destroyOnClose:true,
                      forceRender:true
                    }}
                    visible={this.state.zbNewForm}
                    submitter={this.access==='sale'?false:{
                      render: (props, defaultDoms) => {
                        return <div style={{margin:20}}>{defaultDoms[1]}</div>;
                      }}}
                    formRef={this.tab2FormRef}
                    onFinish={async (values) => {
                      values.dealerId  = this.state.data.dealId
                      var val = await request('/xwyl/sign/addIndicators',{ method: 'POST',
                      requestType:'form',
                      data: values});
                      if(val.errorCode==='200'){
                        message.success('提交成功');
                        this.zbAction.current?.reloadAndRest?.();
                        return true;
                      }else{
                        message.error(val.errorMessage);
                        return false;
                      }
                    }}>
                      <ProFormSelect name='manufacturer' rules={[
                        {
                          required: true,
                        },
                      ]} label='厂家' options={manufacturerOptionArray()}  placeholder='请选择' />
                      <ProFormDatePicker.Year name='year' rules={[
                        {
                          required: true,
                        },
                      ]} label='年份'  placeholder='请选择' />
                    </DrawerForm> */}
                </TabPane>
            </Tabs>
            </ProForm>
        )
    }
}

export default DealerAuth
